/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.invdetail.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.invIn.entity.InvIn;
import vip.xiaonuo.modular.invIn.service.InvInService;
import vip.xiaonuo.modular.invdetail.entity.InvDetail;
import vip.xiaonuo.modular.invdetail.enums.InvDetailExceptionEnum;
import vip.xiaonuo.modular.invdetail.mapper.InvDetailMapper;
import vip.xiaonuo.modular.invdetail.param.InvDetailParam;
import vip.xiaonuo.modular.invdetail.service.InvDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.stockbalance.entity.StockBalance;
import vip.xiaonuo.modular.stockbalance.service.StockBalanceService;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 出入库明细service接口实现类
 *
 * @author wz
 * @date 2022-06-10 14:27:42
 */
@Service
public class InvDetailServiceImpl extends ServiceImpl<InvDetailMapper, InvDetail> implements InvDetailService {

    @Resource
    StockBalanceService stockBalanceService;

    @Resource
    InvInService invInService;

    @Override
    public PageResult<InvDetailParam> page(InvDetailParam invDetailParam) {
        QueryWrapper<InvDetailParam> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(invDetailParam)) {

            // 根据库单编码 查询
            if (ObjectUtil.isNotEmpty(invDetailParam.getInvIds())) {
                queryWrapper.inSql("a.inv_id", invDetailParam.getInvIds());
            }
            // 根据产品名称 查询
            if (ObjectUtil.isNotEmpty(invDetailParam.getProIds())) {
                queryWrapper.inSql("a.pro_id", invDetailParam.getProIds());
            }
            //根据明细来源查询
            if (ObjectUtil.isNotEmpty(invDetailParam.getCategory())) {
                queryWrapper.eq("c.category", invDetailParam.getCategory());
            }
            if (ObjectUtil.isNotEmpty(invDetailParam.getInTypes())&&ObjectUtil.isNotEmpty(invDetailParam.getOutTypes()))
            {
                String[] inTypeList = invDetailParam.getInTypes().split(",");
                String[] outTypeList = invDetailParam.getOutTypes().split(",");
                queryWrapper.in("c.in_type", inTypeList).or().in("c.out_type", outTypeList);;
            }
            else
            {
                //根据入库类型查询
                if (ObjectUtil.isNotEmpty(invDetailParam.getInTypes())) {
                    String[] inTypeList = invDetailParam.getInTypes().split(",");
                    queryWrapper.in("c.in_type", inTypeList);
                }
                //根据出库类型查询
                if (ObjectUtil.isNotEmpty(invDetailParam.getOutTypes())) {
                    String[] outTypeList = invDetailParam.getOutTypes().split(",");
                    queryWrapper.in("c.out_type", outTypeList);
                }
            }

            // 根据入库时间 查询
            if (ObjectUtil.isNotEmpty(invDetailParam.getTime())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                try {
                    date = sdf.parse(invDetailParam.getTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //得到日历
                Calendar calendar = Calendar.getInstance();
                //把当前时间赋给日历
                calendar.setTime(date);
                queryWrapper.ge("c.time",sdf.format(calendar.getTime()));
                //设置为后一天
                calendar.add(Calendar.DAY_OF_MONTH, +1);
                queryWrapper.lt("c.time",sdf.format(calendar.getTime()));
            }
        }
        queryWrapper.orderByDesc("a.create_time");
        return new PageResult<>(this.baseMapper.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<InvDetail> list(InvDetailParam invDetailParam) {
        return this.list();
    }

    @Override
    public void add(InvDetailParam invDetailParam) {
        InvDetail invDetail = new InvDetail();
        BeanUtil.copyProperties(invDetailParam, invDetail);
        this.save(invDetail);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<InvDetailParam> invDetailParamList) {
        invDetailParamList.forEach(invDetailParam -> {
            /*
             * =======================================库存余额逻辑 start =====================================
             */
            //根据明细ID查询数据库中的明细的所有数据
            InvDetail invDetail = this.getById(invDetailParam.getId());
            //修改根据仓库id和产品id修改仓库余额
            QueryWrapper<StockBalance> sbqw = new QueryWrapper<>();
            sbqw.lambda().eq(StockBalance::getWarHouId,invDetail.getWarHouId());
            sbqw.lambda().eq(StockBalance::getProId,invDetail.getProId());
            StockBalance stockBalance = stockBalanceService.getOne(sbqw);
            // 基本上不可能有这个错误
            if (ObjectUtil.isEmpty(stockBalance)){
                throw new ServiceException(4,"谁偷偷的删除了仓库？？？？");
            }
            //获取出入库类型   因为入库出库是一个表，所有用 invInService或者invOutService 都可以
            int category = invInService.getById(invDetail.getInvId()).getCategory();
            // 如果仓库余额为0，那直接删除仓库
            if (stockBalance.getStoNum()+invDetail.getNum()*-1*category == 0){
                stockBalanceService.removeById(stockBalance.getId());
            }
            //否则进行修改
            stockBalance.setStoNum(stockBalance.getStoNum()+invDetail.getNum()*-1*category);
            stockBalanceService.updateById(stockBalance);
            /*
             * =======================================库存余额逻辑 end =====================================
             */
            this.removeById(invDetailParam.getId());
        });
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(InvDetailParam invDetailParam) {
        InvDetail invDetail = this.queryInvDetail(invDetailParam);
        BeanUtil.copyProperties(invDetailParam, invDetail);
        this.updateById(invDetail);
    }

    @Override
    public InvDetail detail(InvDetailParam invDetailParam) {
        return this.queryInvDetail(invDetailParam);
    }

    /**
     * 获取出入库明细
     *
     * @author wz
     * @date 2022-06-10 14:27:42
     */
    private InvDetail queryInvDetail(InvDetailParam invDetailParam) {
        InvDetail invDetail = this.getById(invDetailParam.getId());
        if (ObjectUtil.isNull(invDetail)) {
            throw new ServiceException(InvDetailExceptionEnum.NOT_EXIST);
        }
        return invDetail;
    }

    @Override
    public void export(InvDetailParam invDetailParam) {
        List<InvDetail> list = this.list(invDetailParam);
        PoiUtil.exportExcelWithStream("SnowyInvDetail.xls", InvDetail.class, list);
    }

}
